//
// Created by Administrator on 2024/4/16.
// 链表头结点指向的结点索引为0, 交换两个给定索引的链表
//

#include <iostream>
#include <vector>
#include "linkedListUtil.h"

using namespace std;


// a,b 为要交换的两个结点的索引,从0开始
// 变更结点的值
bool swapNode01(Node *h, int a, int b)
{
    if (a == b || h->next == nullptr)
        return true;
    if (a > b)
        swap(a, b);
    Node *preA = h;
    Node *cur = h->next;
    int i = 0;
    for (; i < a; ++i)
    {
        if (cur == nullptr)
            return false;
        preA = preA->next;
        cur = cur->next;
    }
    Node *preB = preA;
    for (; i < b; ++i)
    {
        if (cur == nullptr)
            return false;
        preB = preB->next;
        cur = cur->next;
    }
    swap(preA->next->v, preB->next->v);
    return true;
}

// 交换第a个和后边一个结点 变更指向
bool swapNeighbor01(Node *h, int a)
{
    Node *pre = h;
    Node *cur = h->next;
    for (int i = 0; i < a; ++i)
    {
        pre = pre->next;
        // 到链表结尾 就不能再交换了 返回false
        if (pre->next->next== nullptr)
            return false;
        cur=cur->next;
    }
    pre->next=cur->next;
    cur->next=pre->next->next;
    pre->next->next=cur;
    return true;
}

int main()
{
    vector<int> l{0,1, 2, 3, 4, 5, 6};
    Node *h = build(l);
    printLinkedList(h);
//    swapNode01(h, 0, 30);
    cout<<swapNeighbor01(h,5)<<endl;
    printLinkedList(h);
    return 0;
}